package P8;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/**
 * 使用Java中的UDP套接字实现文件上传的客户端和服务端程序
 * 8.1客户端程序
 */
public class UDPFileClient {
    public static void main(String[] args) {
        try {
            // 创建DatagramSocket
            DatagramSocket clientSocket = new DatagramSocket();

            // 指定服务端IP和端口
            InetAddress serverAddress = InetAddress.getByName("localhost");
            int serverPort = 12345;

            // 要上传的文件
            File file = new File("path/to/your/file.txt");
            byte[] fileBytes = new byte[(int) file.length()];

            // 读取文件内容到字节数组
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
                bis.read(fileBytes);
            }

            // 将文件字节数组分成多个数据包发送
            int packetSize = 1024;
            int numPackets = (int) Math.ceil((double) fileBytes.length / packetSize);

            for (int i = 0; i < numPackets; i++) {
                int start = i * packetSize;
                int end = Math.min((i + 1) * packetSize, fileBytes.length);
                byte[] packetData = new byte[end - start];
                System.arraycopy(fileBytes, start, packetData, 0, packetData.length);

                DatagramPacket packet = new DatagramPacket(packetData, packetData.length, serverAddress, serverPort);
                clientSocket.send(packet);
            }

            System.out.println("File uploaded successfully!");
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}